# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/2/28
# @File   : EC01_CreditBusinessLoanOrgCnt.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:报告期内信贷业务机构数量
code:EC01_CreditBusinessLoanOrgCnt
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ
type:常用指标
dataSourceType:在线指标 description:这是获取 EC01 字段的数据脚本
eof'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = EC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['ReportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def isfloat(x):

    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def EC01_CreditBusinessLoanOrgCnt():
    try:
        ECRSummaryDesc = getTable('ECRSummaryDesc')

        if ECRSummaryDesc is None or ECRSummaryDesc == [{}]:
            return u'缺失值'
        else:
            pattern = u'[\s+\.\!\/_,$%^*(+\"\')]+|[+——()?【】“”！，。？、~@#￥%……&*（） ]+'
            pattern1 = u'信息主体未与金融机构发生过信贷关系'
            pattern2 = u'共在([0-9]+)家金融机构办理过信贷业务'

            descLine = ECRSummaryDesc[0].get('BriefDesc')

            if descLine not in null_type_list:

                if pattern1 in descLine:
                    return u'缺失值'
                else:
                    r1 = re.compile(pattern)
                    #去掉非中文和数字的字符
                    descLineTmp = r1.sub(u'', descLine)
                    r2 = re.compile(pattern2)
                    if r2.finditer(descLineTmp):
                        g = list(r2.finditer(descLineTmp))[0].group(1)
                        return float(g)
                    else:
                        return u'缺失值'

            else:
                return u'缺失值'
    except:
        return u'缺失值'

result = EC01_CreditBusinessLoanOrgCnt()